package com.woniu.idearbac.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.idearbac.util.JwtUtils;
import com.woniu.idearbac.util.Result;
import com.woniu.idearbac.vo.PermissionVo;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 功能描述
 *
 * @author PC
 * @date -2022/12/1-时间-17:51
 * @product idea-rbac
 */
public class SuccessSecurity extends SimpleUrlAuthenticationSuccessHandler {
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private RedisCache redisCache;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        SecurityContextHolder.getContext().setAuthentication(authentication);//采用threadLocal模型
        LoginUser user = (LoginUser) authentication.getPrincipal();
        String token = jwtUtils.generateToken(user.getUsername());
        //把loginUser保存到redis中，七天后过期，减少每次请求对mysql的读操作
        redisCache.setCacheObject("rbac:"+user.getUsername(),user,7, TimeUnit.DAYS);
        List<PermissionVo> menuList = user.getMenuList();
        response.setContentType("application/json;charset=utf-8");
        String string = new ObjectMapper().writeValueAsString(Result.ok().data("menuList",menuList).data("token",token).data("userdata",user.getUser()));
        response.getWriter().println(string);
    }
}
